package com.jushu.storbox.adapter;

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.callback.IUploadCallback;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.task.tqueue.UploadTask;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class UploadListAdapter extends BaseAdapter
{
    private Context context;
    
    private ViewHolder holder;
    
    private List<FileInfo> fileList;
    
    private ICloudDriveService cloudDriveService;
    
    private final static String LOG_TAG = "UploadListAdapter";
    
    private Handler handler;
    
    public UploadListAdapter(Context context, List<FileInfo> fileList, ICloudDriveService cloudDriveService,
        Handler handler)
    {
        this.context = context;
        this.fileList = fileList;
        this.cloudDriveService = cloudDriveService;
        this.handler = handler;
    }
    
    @Override
    public int getCount()
    {
        // TODO Auto-generated method stubc
        return fileList.size();
    }
    
    @Override
    public Object getItem(int position)
    {
        // TODO Auto-generated method stub
        return fileList.get(position);
    }
    
    @Override
    public long getItemId(int position)
    {
        // TODO Auto-generated method stub
        return position;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        // TODO Auto-generated method stub
        if (null == convertView)
        {
            convertView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_uploadlist,
                null);
            holder = new ViewHolder();
            
            holder.item_uploadlist_img_re = (RelativeLayout) convertView.findViewById(R.id.item_uploadlist_re);
            holder.item_uploadlist_progress = (ProgressBar) convertView.findViewById(R.id.item_uploadlist_progress_horizontal);
            holder.item_uploadlist_name_text = (TextView) convertView.findViewById(R.id.item_uploadlist_name_text);
            holder.item_uploadlist_file_size = (TextView) convertView.findViewById(R.id.item_uploadlist_file_size);
            holder.item_uploadlist_more_tv = (TextView) convertView.findViewById(R.id.item_uploadlist_more_tv);
            holder.item_uploadlist_type_img = (ImageView) convertView.findViewById(R.id.item_uploadlist_type_img);
            holder.item_upload_state_button = (Button) convertView.findViewById(R.id.item_upload_state_button);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.fileInfo = fileList.get(position);
        final ViewHolder holder2 = holder;
        final View convertView2 = convertView;
        inituploadTask(holder); 
        initUploadStatus(holder);
        holder.item_uploadlist_type_img.setImageResource(R.mipmap.default_file_icon);
        holder.item_uploadlist_name_text.setText(holder.fileInfo.getName());
        holder.item_uploadlist_file_size.setText(PublicTools.changeBKM(holder.fileInfo.getSize() + ""));
        holder.item_upload_state_button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                deleteButtonClick(holder2, convertView2);
            }
        });
        holder.item_uploadlist_img_re.setOnClickListener(new View.OnClickListener()
        {
            
            @Override
            public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                itemClick(holder2);
            }
        });
        return convertView;
    }
    
    private void itemClick(ViewHolder holder)
    {
        if (holder.uploadState == 2)
        {
            final iFileManager mdmTools = FileManagerFactory.getFileManager(context);
            LogUtil.i(LOG_TAG, "openpath:" + holder.fileInfo.getLoctPath());
            if (null != mdmTools)
            {
                mdmTools.openFile(holder.fileInfo.getLoctPath(), holder.fileInfo.getSize());
            }
        }
        
    }
    
    private void deleteButtonClick(final ViewHolder holder2, final View convertViews)
    {
        // TODO Auto-generated method stub
        
        final ClouddriveDialog delete = new ClouddriveDialog(context, R.style.dialog_upload,
            R.layout.dialog_filedelete);
        View conventView = delete.getConventView();
        Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
        Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);
        TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
        dialog_prompt_tv.setText(context.getString(R.string.allfile_confirm_delete_filefolder));
        dialog_cancal.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                delete.dismiss();
            }
        });
        
        dialog_OK.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                delete.dismiss();
                holder2.uploadTask = cloudDriveService.getUploadTask(holder2.fileInfo.getLoctPath());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = convertViews;
                handler.sendMessage(msg);
                if (holder2.uploadState == 0)
                {
                    if (null != holder2.uploadTask)
                    {
                    }
                    cloudDriveService.deleteDownloadFile(holder2.fileInfo.getId());
                }
                else if (holder2.uploadState == 1)
                {
                    if (null != holder2.uploadTask)
                    {
                    }
                    cloudDriveService.deleteDownloadFile(holder2.fileInfo.getId());
                }
                else if (holder2.uploadState == 2)
                {
                    cloudDriveService.deleteDownloadFile(holder2.fileInfo.getId());
                }
            }
        });
        delete.show();
    }
    
    private void initUploadStatus(final ViewHolder holder)
    {
        // TODO Auto-generated method stub
        if (holder.fileInfo.getTransStatus() == 1)
        {// waiting。。。
            Message msg = new Message();
            msg.what = 1;
            holder.handler.sendMessage(msg);
        }
        else if (holder.fileInfo.getTransStatus() == 2)
        {// uploading
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    // TODO Auto-generated method stub
                    // cache upload status
                    if (null != holder.uploadTask)
                    {
                        try
                        {
                            holder.uploadTask.setCallback(holder.uploadCallback);
                        }
                        catch (Exception e)
                        {
                            // TODO: handle exception
                            LogUtil.e(LOG_TAG,
                                "download task set callback fail message:" + e.getLocalizedMessage());
                        }
                    }
                }
            }).start();
            Message msg = new Message();
            msg.what = 2;
            holder.handler.sendMessage(msg);
        }
        else if (holder.fileInfo.getTransStatus() == 3)
        { // upload finish
            Message msg = new Message();
            msg.what = 3;
            holder.handler.sendMessage(msg);
        }
    }
    
    /**
     * init downloadtask
     * */
    private void inituploadTask(final ViewHolder viewHolder)
    {
        // TODO Auto-generated method stub
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                // LogUtil.i(TAG, "initDownloadTask...");
                try
                {
                    if (null != cloudDriveService)
                    {
                        UploadTask uploadTask = cloudDriveService.getUploadTask(viewHolder.fileInfo.getLoctPath());
                        if (null != uploadTask)
                        {
                            uploadTask.setCallback(viewHolder.uploadCallback);
                        }
                    }
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    e.printStackTrace();
                    viewHolder.uploadTask = null;
                    LogUtil.e(LOG_TAG, "inituploadTask fail..." + e.getLocalizedMessage());
                }
            }
        }).start();
    }
    
    public class ViewHolder
    {
        public FileInfo fileInfo;
        
        public UploadTask uploadTask;
        
        public RelativeLayout item_uploadlist_img_re;
        
        public ProgressBar item_uploadlist_progress;
        
        public TextView item_uploadlist_name_text;
        
        public TextView item_uploadlist_file_size;
        
        public TextView item_uploadlist_more_tv;
        
        public ImageView item_uploadlist_type_img;
        
        public Button item_upload_state_button;
        
        public int uploadState = 0;
        
        Handler handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                switch (msg.what)
                {
                    case 1:
                        item_uploadlist_progress.setVisibility(View.GONE); 
                        item_uploadlist_more_tv.setVisibility(View.VISIBLE);
                        item_uploadlist_more_tv.setText("Waiting upload...");
                        item_upload_state_button.setText("Cancel");
                        uploadState = 0;
                        break;
                    case 2:// Uploading
                        item_uploadlist_progress.setVisibility(View.VISIBLE);
                        item_uploadlist_more_tv.setVisibility(View.GONE);
                        item_upload_state_button.setText("Cancel");
                        uploadState = 1;
                        break;
                    case 3:// Upload finish
                        item_uploadlist_progress.setVisibility(View.GONE); 
                        item_uploadlist_more_tv.setVisibility(View.VISIBLE);
                        item_uploadlist_more_tv.setText(PublicTools.longToString((long) fileInfo.getLastUpdateDate()));
                        item_upload_state_button.setText("Clear");
                        uploadState = 2;
                        break;
                    default:
                        break;
                }
            };
        };
        
        // Upload Callback
        IUploadCallback uploadCallback = new IUploadCallback()
        {
            @Override
            public void onSuccess(FileInfoResponseV2 successItem)
            {
                // TODO Auto-generated method stub
                Message msg = new Message();
                msg.what = 2;
                uploadhandler.sendMessage(msg);
                Log.e("~~", "Upload Success");
                LogUtil.i(LOG_TAG, "uploadCallback upload success");
            }
            
            @Override
            public void onStart()
            {
                // TODO Auto-generated method stub
                LogUtil.i(LOG_TAG, "uploadCallback start upload");
            }
            
            @Override
            public void onProgress(int currentProgress, long currentSize, long maxSize)
            {
                // TODO Auto-generated method stub
                Message msg = new Message();
                msg.what = 1;
                msg.arg1 = currentProgress;
                msg.arg2 = (int) currentSize;
                uploadhandler.sendMessage(msg);
                LogUtil.i(LOG_TAG, "currentProgress:" + currentProgress);
            }
            
            @Override
            public void onFailure(Throwable t)
            {
                // TODO Auto-generated method stub
                Message msg = new Message();
                msg.what = 3;
                uploadhandler.sendMessage(msg);
                Log.e("~~", "Upload Fail");
                LogUtil.e(LOG_TAG,
                    "upload final Message:" + t.getMessage() + ",LocalizedMessage:" + t.getLocalizedMessage());
            }

			@Override
			public void onStop() {
			}

			@Override
			public void onCanceled() {
			}

			@Override
			public void onDettach() {
			}
        };
        
        Handler uploadhandler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                switch (msg.what)
                {
                    case 1:
                        item_uploadlist_progress.setMax(100);
                        item_uploadlist_progress.setSecondaryProgress(msg.arg1);
                        Log.e("~~", "Uploading, currentProgress：" + msg.arg1);
                        item_uploadlist_file_size.setText(PublicTools.changeBKM(msg.arg2 + "") + "%"
                            + PublicTools.changeBKM(fileInfo.getSize() + ""));
                        item_upload_state_button.setText("Cancel");
                        uploadState = 1;
                        break;
                    case 2:// Upload finish
                        item_uploadlist_progress.setVisibility(View.GONE); 
                        item_uploadlist_more_tv.setVisibility(View.VISIBLE);
                        item_uploadlist_more_tv.setText(PublicTools.longToString((long) fileInfo.getLastUpdateDate()));
                        item_upload_state_button.setText("Clear");
                        cloudDriveService.updateDownloadState(fileInfo.getId(), 3); 
                        item_uploadlist_file_size.setText(PublicTools.changeBKM(fileInfo.getSize() + ""));
                        uploadState = 2;
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            }
        };
    }
}
